using GlobalData;
using Model.Core.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Polly;

namespace RobotClient.Controllers
{
    public class RobotMqHelperCtrl:IHostedService
    {



        private readonly ILogger<RobotMqHelperCtrl> _logger;

        public RobotMqHelperCtrl(
            LocalMqClientCtrl localMqClientCtrl,
            CloudMqClientCtrl cloudMqClientCtrl,
            IConfiguration configuration,
            MqTopics globalMqTopics,
            ILogger<RobotMqHelperCtrl> logger)
        {
            _logger = logger;
            _Configuration = configuration;
            _GlobalMqTopics = globalMqTopics;
            _LocalMqClientCtrl = localMqClientCtrl;
            _CloudMqClientCtrl = cloudMqClientCtrl;
        }







        private void MqMsgRecvEventFunc()
        {
            _CloudMqClientCtrl.MsgReceivedEvent += async (a, b) =>
            {
                try
                {
                    _logger.LogInformation("Received Topic:{Topic} Payload:{Payload}", a, b);
                    if (MqTopics.RobotBaseInfoGet_Topic.Equals(a))
                    {
                        IConfiguration localstr = _Configuration.GetSection("RobotInfo");
                        string robotId = localstr.GetSection("RobotId").Value.ToString();
                        string Name = localstr.GetSection("RobotName").Value.ToString();
                        string Type = localstr.GetSection("RobotType").Value.ToString();
                        var jsondata = new JObject();
                        jsondata["name"] = Name;
                        jsondata["id"] = robotId;
                        jsondata["type"] = Type;
                        await _CloudMqClientCtrl.SendMessageAsync(MqTopics.RobotBaseInfoPub_Topic, jsondata.ToString()).ConfigureAwait(false);

                    }

                    else if (_GlobalMqTopics.Jack_ctrl_Topic.Equals(a))
                    {
                        await _LocalMqClientCtrl.SendMessageAsync(MqTopics.md_robot_jack_ctrl_Topic, b).ConfigureAwait(false);
                    }
                    else if (_GlobalMqTopics.RobotCommandTopic.Equals(a))
                    {
                        await _LocalMqClientCtrl.SendMessageAsync(MqTopics.StackerLiftingCtrl_Client, b).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "MqMsgRecvEventFunc Error");
                }
                ;
            };

            _LocalMqClientCtrl.MsgReceivedEvent += async (a, b) =>
            {
                try
                {
                    if (MqTopics.StackerLiftingInfo_Client.Equals(a))
                    {
                        var jArray = JsonConvert.DeserializeObject<JArray>(b);
                        var jobject = new JObject();
                        jArray?.ToList().ForEach(a =>
                        {
                            var jobj = a as JObject;
                            var name = jobj?["name"]?.ToString();
                            if (!string.IsNullOrEmpty(name))
                            {
                                jobject.Add(name, jobj?["value"]?.ToString());
                            }

                        });
                        _ = _CloudMqClientCtrl.SendMessageAsync(_GlobalMqTopics.RobotStatusTopic, JsonConvert.SerializeObject(jobject)).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {

                    _logger.LogError(ex, "MqMsgRecvEventFunc Error");
                }

            };
        }

        private async void AddSubMqFunc()
        {
            try
            {
                //using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));

                #region 订阅云端消息
                var cloudTopics = new[] {
                    MqTopics.RobotBaseInfoGet_Topic,
                    _GlobalMqTopics.RobotCommandTopic,
                    _GlobalMqTopics.Jack_ctrl_Topic
                };
               await _CloudMqClientCtrl.AddSubTopics(cloudTopics).ConfigureAwait(false);          
                #endregion

                #region 订阅本地消息
                var LocalTopics = new[] {
                    MqTopics.StackerLiftingInfo_Client,
                    _GlobalMqTopics.Job_Ctrl_Topic,
                };
                _ = _LocalMqClientCtrl.AddSubTopics(LocalTopics).ConfigureAwait(false); 
                #endregion
            }
            catch (OperationCanceledException ex)
            {
                _logger.LogError(ex, "MQTT订阅操作超时");
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, "MQTT订阅初始化失败");
            }
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("MqClient Started at {Time}", DateTime.Now.ToString("yyyyMMdd HH:mm:ss:ff"));
            AddSubMqFunc();
            MqMsgRecvEventFunc();
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("MqClient Stopped at {Time}", DateTime.Now.ToString("yyyyMMdd HH:mm:ss:ff"));
            await Task.CompletedTask.ConfigureAwait(false);
        }


        // private static readonly ObjectPool<JObject> _jsonObjectPool = ObjectPool.Create<JObject>(() => new JObject());
        // private static readonly ObjectPool<JArray> _jsonArrayPool = ObjectPool.Create<JArray>(() => new JArray());

        public IConfiguration _Configuration { get; }
        public MqTopics _GlobalMqTopics { get; }
        /// <summary>
        /// 本地通信mqtt_client
        /// </summary>
        public MqClientCtrl _LocalMqClientCtrl { get; }
        /// <summary>
        /// 云通信mqtt_client
        /// </summary>
        public MqClientCtrl _CloudMqClientCtrl { get; }



    }
}
